package com.cyh.nio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;

/**
 *  异步读2
 * */
public class AsyncFileChannelDemo02 {


    public static void main(String[] args) throws Exception {
       //1 创建AsynchronousFileChannel
        Path path = Paths.get("D:\\cyh\\work_java\\TestNioOrIo\\src\\com\\cyh\\5.txt");
        AsynchronousFileChannel fileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);

        //2 创建Buffer
        ByteBuffer buffer = ByteBuffer.allocate(1024);

        //3 调用channel的read方法得到Future
        fileChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
                System.out.println(result);
                buffer.flip();

                byte[] data = new byte[attachment.limit()];
                attachment.get(data);
                System.out.println(new String(data));

                attachment.clear();
            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {

            }
        });



    }
}
